<template>
    <view class="complete-info-container">
        <!-- 头像上传区域 -->
        <view class="avatar-section">
            <view class="avatar-wrapper" @click="chooseAvatar">
                <image 
                    :src="userInfo.avatar || 'https://puqinzc.oss-cn-beijing.aliyuncs.com/d0c6fee22789b9b8b14ab0e5b9fbf761.png'" 
                    mode="aspectFill" 
                    class="avatar-image"
                ></image>
                <view class="avatar-edit-icon">
                    <image src="../../static/edit.png" mode="widthFix" class="edit-icon"></image>
                </view>
            </view>
            <text class="avatar-tip">点击更换头像</text>
        </view>

        <!-- 表单区域 -->
        <view class="form-section">
            <view class="form-item">
                <view class="form-label">姓名</view>
                <input 
                    v-model="userInfo.realName" 
                    placeholder="请输入姓名" 
                    class="form-input"
                    maxlength="20"
                />
            </view>

            <view class="form-item disabled">
                <view class="form-label">手机号</view>
                <input 
                    v-model="userInfo.contactPhone" 
                    placeholder="请输入手机号" 
                    class="form-input"
                />
                <!-- <text class="disabled-tip">手机号不可修改</text> -->
            </view>
        </view>

        <!-- 保存按钮 -->
        <view class="save-section">
            <button @click="saveUserInfo" class="save-btn">保存修改</button>
        </view>
    </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { editUserInfo } from '@/utils/api.js'
import {  uploadFile, imageUrl } from '@/utils/request.js'
// 用户信息
const userInfo = reactive({
    avatar: '',
    realName: '',
    contactPhone: ''
})

// 从localStorage获取用户信息的辅助函数
const getUserInfoFromStorage = () => {
    try {
        const userInfoStr = uni.getStorageSync('user_info')
        if (userInfoStr) {
            // 如果是字符串，转换为 JSON 对象
            if (typeof userInfoStr === 'string') {
                try {
                    return JSON.parse(userInfoStr)
                } catch (parseError) {
                    console.error('解析用户信息失败:', parseError)
                    return null
                }
            }
            return userInfoStr
        }
        return null
    } catch (error) {
        console.error('获取用户信息失败:', error)
        return null
    }
}

// 页面加载时获取用户信息
onMounted(() => {
    loadUserInfo()
    console.log(imageUrl)
})

// 从localStorage加载用户信息
const loadUserInfo = () => {
    try {
        const userInfoData = getUserInfoFromStorage()
        if (userInfoData) {
            userInfo.avatar = userInfoData.avatar || 'https://puqinzc.oss-cn-beijing.aliyuncs.com/d0c6fee22789b9b8b14ab0e5b9fbf761.png'
            userInfo.realName = userInfoData.name || ''
            userInfo.contactPhone = userInfoData.phone || ''
        }
    } catch (error) {
        console.error('加载用户信息失败:', error)
        // 使用默认头像
        userInfo.avatar = 'https://puqinzc.oss-cn-beijing.aliyuncs.com/d0c6fee22789b9b8b14ab0e5b9fbf761.png'
    }
}

// 选择头像
const chooseAvatar = () => {
    uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
            const tempFilePath = res.tempFilePaths[0]
            
            // 显示上传中提示
            uni.showLoading({
                title: '上传中...'
            })
            
            try {
                // 上传头像到服务器
                const uploadRes = await uploadFile(tempFilePath, 'image')
                // 更新头像
                userInfo.avatar = imageUrl + uploadRes.key
                
                uni.showToast({
                    title: '头像上传成功',
                    icon: 'success'
                })
                    
            } catch (error) {
                console.error('上传头像失败:', error, imageUrl)
                uni.showToast({
                    title: '上传头像失败',
                    icon: 'error'
                })
            } finally {
                uni.hideLoading()
            }
        },
        fail: (err) => {
            console.error('选择头像失败:', err)
            uni.showToast({
                title: '选择头像失败',
                icon: 'error'
            })
        }
    })
}

// 保存用户信息
const saveUserInfo = async () => {
    if (!userInfo.realName.trim()) {
        uni.showToast({
            title: '请输入姓名',
            icon: 'error'
        })
        return
    }

    // 显示加载状态
    uni.showLoading({
        title: '保存中...'
    })

    try {
        // 构建提交数据，只提交指定字段
        const currentUserInfo = getUserInfoFromStorage()
        const submitData = {
            ...currentUserInfo,
            name: userInfo.realName.trim(),
            phone: userInfo.contactPhone || '',
            avatar: userInfo.avatar
        }
        
        // 调用编辑用户信息接口
        const res = await editUserInfo(submitData)
        uni.hideLoading()
        
        if (res.code === 0) {
            // 更新localStorage中的用户信息
            try {
                const currentUserInfo = getUserInfoFromStorage()
                const updatedUserInfo = currentUserInfo ? 
                    { ...currentUserInfo, ...submitData } : 
                    submitData

                uni.setStorageSync('user_info', updatedUserInfo)
            } catch (error) {
                console.error('更新本地用户信息失败:', error)
            }
            
            uni.showToast({
                title: '保存成功',
                icon: 'success'
            })
        } else {
            uni.showToast({
                title: res.msg || '保存失败',
                icon: 'error'
            })
        }
    } catch (error) {
        console.error('保存用户信息失败:', error)
        uni.showToast({
            title: '网络错误，请重试',
            icon: 'error'
        })
    } 
}
</script>

<style lang="scss" scoped>
.complete-info-container {
    min-height: 100vh;
    // background: linear-gradient(180deg, #FFE9DA 0%, #F8F9FB 100%);
    padding: 0 24rpx;
}

.avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 80rpx 0 60rpx;
    
    .avatar-wrapper {
        position: relative;
        width: 160rpx;
        height: 160rpx;
        border-radius: 50%;
        overflow: hidden;
        border: 4rpx solid #fff;
        box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
        
        .avatar-image {
            width: 100%;
            height: 100%;
        }
        
        .avatar-edit-icon {
            position: absolute;
            bottom: 0;
            right: 0;
            width: 48rpx;
            height: 48rpx;
            background: rgba(0, 0, 0, 0.6);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            
            .edit-icon {
                width: 24rpx;
                height: 24rpx;
            }
        }
    }
    
    .avatar-tip {
        margin-top: 16rpx;
        font-size: 24rpx;
        color: #666;
    }
}

.form-section {
    background: #fff;
    border-radius: 16rpx;
    padding: 0 24rpx;
    margin-bottom: 40rpx;
    
    .form-item {
        display: flex;
        align-items: center;
        padding: 32rpx 0;
        border-bottom: 1rpx solid #F0F0F0;
        position: relative;
        
        &:last-child {
            border-bottom: none;
        }
        
        &.disabled {
            .form-input {
                color: #999;
                // background: #F8F8F8;
            }
        }
        
        .form-label {
            width: 120rpx;
            font-size: 28rpx;
            color: #333;
            font-weight: 500;
        }
        
        .form-input {
            flex: 1;
            height: 48rpx;
            font-size: 28rpx;
            color: #333;
            padding: 0 16rpx;
            border: none;
            outline: none;
        }
        
        .disabled-tip {
            position: absolute;
            right: 0;
            font-size: 22rpx;
            color: #999;
        }
    }
}

.save-section {
    padding: 40rpx 0;
    
    .save-btn {
        width: 100%;
        height: 88rpx;
        background: linear-gradient(135deg, #FC8759 0%, #FF6B35 100%);
        border-radius: 44rpx;
        color: #fff;
        font-size: 32rpx;
        font-weight: 500;
        border: none;
        box-shadow: 0 8rpx 24rpx rgba(252, 135, 89, 0.3);
        
        &:active {
            transform: scale(0.98);
        }
    }
}
</style>
